package com.tyj.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tyj.common.constant.AuthServerConstant;
import com.tyj.common.utils.HttpUtils;
import com.tyj.common.utils.R;
import com.tyj.gulimall.auth.feign.MemberFeignService;
import com.tyj.common.vo.MemberRespVo;
import com.tyj.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 社交登录请求
 */
@Controller
@Slf4j
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        //发送请求  根据code换取accessToken
        Map<String,String> map=new HashMap<>();
        map.put("client_id","3118452339");
        map.put("client_secret","926998b51ddfa9b0709eac76884e55fa");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        Map map1=new HashMap();
        HttpResponse response = HttpUtils.doPost( "https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), map, new HashMap<String, String>());
        //2.处理
        if (response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户
            //如果当前用户是第一次进网站,自动注册 否则在数据库查询该用户
            R login=null;
            try{
                login = memberFeignService.login(socialUser);
                if (login.getCode()==0){
                    //登录成功跳回首页
                    MemberRespVo data = login.getData(new TypeReference<MemberRespVo>() {});
                    session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                    log.debug("登录的用户是{}",data);
                    return "redirect:http://gulimall.com";
                }else {
                    //登录失败
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("调用member登录服务失败{}",e.getMessage());
                //登录失败
                return "redirect:http://auth.gulimall.com/login.html";
            }

        }else {
            //获取验证令牌失败
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

}
